package com.atguigu.spzx.cloud.gateway.filters;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * projectName: com.atguigu.spzx.cloud.gateway.filters
 *
 * @author: 赵伟风
 * description:
 *
 * 1.创建过滤器类
 * 2.实现接口
 * 3.实现过滤业务
 * 4.添加到ioc容器
 */
@Component
public class LoginProtectedFilter  implements GlobalFilter , Ordered {
    /**
     *
     * file -> doFilter(request,response,fileChain) -> fileChain.doFilter(request,response);
     *
     * 拦截和过滤器逻辑
     *    过滤逻辑
     *    决定： 放行 还是 拦截
     * @param exchange  ServerWebExchange = request+response 请求和响应的封装对象
     * @param chain GatewayFilterChain 这就是网关的过滤连，可以进行放行 chain.filter(exchange)放行
     * @return  Mono<Void> == void => Mono异步方法的返回值描述
     */
    //GlobalFilter 提供的
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //检查参数中是否有username 有放行，没有给与未登录状态码 401
        String username = exchange.getRequest().getQueryParams().getFirst("username");
        if (ObjectUtils.isEmpty(username)){
            //拦截
            //exchange.getResponse().setRawStatusCode(401);
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);//401
            //拦截 【指定一个状态码 || 这次请求到这你就结束了】
            return exchange.getResponse().setComplete(); //这次请求到这你就结束了 200
        }
        //放行 【往下走】
        return chain.filter(exchange);
    }

    //Ordered 设置优先级 0 - 100  0最大
    @Override
    public int getOrder() {
        return 0;
    }
}
